import 'package:get/get.dart';
import 'package:flutter/services.dart';
import '../utils/toast_util.dart';
import '../config/wechat_config.dart';
import '../widgets/wechat_share_dialog.dart';
import '../models/index.dart';
import '../api/share_api.dart';
import 'share_page_generator_service.dart';
import 'user_service.dart';
import 'dart:developer' as developer;

/// 🔥 原生微信分享服务
/// 
/// 基于Android原生微信SDK实现，避免Flutter插件兼容性问题
/// 通过Method Channel与原生代码通信
class NativeWeChatShareService extends GetxService {
  static const platform = MethodChannel('wechat_share');
  
  /// 服务初始化状态
  final RxBool _isInitialized = false.obs;
  bool get isInitialized => _isInitialized.value;
  
  /// 微信是否已安装
  final RxBool _isWeChatInstalled = false.obs;
  bool get isWeChatInstalled => _isWeChatInstalled.value;

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initWeChatSDK();
  }

  /// 初始化微信SDK
  Future<void> _initWeChatSDK() async {
    try {
      developer.log('🔥 开始初始化原生微信SDK...');
      
      // 调用原生方法初始化微信API
      final success = await platform.invokeMethod('initWeChatAPI');
      _isInitialized.value = success ?? false;
      
      if (_isInitialized.value) {
        // 检查微信是否安装
        final isInstalled = await platform.invokeMethod('isWeChatInstalled');
        _isWeChatInstalled.value = isInstalled ?? false;
        
        // 获取微信支持的API版本
        final apiVersion = await platform.invokeMethod('getWXAppSupportAPI');
        developer.log('📱 微信API版本: $apiVersion');
      }
      
      developer.log('${_isInitialized.value ? "✅" : "❌"} 原生微信SDK初始化${_isInitialized.value ? "成功" : "失败"}');
      developer.log('📱 微信是否已安装: ${_isWeChatInstalled.value}');
      
    } catch (e) {
      developer.log('❌ 原生微信SDK初始化失败: $e');
      _isInitialized.value = false;
      _isWeChatInstalled.value = false;
    }
  }

  /// 分享网页链接到微信
  /// 
  /// [title] 分享标题
  /// [description] 分享描述
  /// [webUrl] 分享的网页链接
  /// [thumbUrl] 缩略图URL（可选）
  /// [isTimeline] 是否分享到朋友圈
  Future<bool> shareWebPage({
    required String title,
    required String description, 
    required String webUrl,
    String? thumbUrl,
    required bool isTimeline,
  }) async {
    try {
      // 检查初始化状态
      if (!_isInitialized.value) {
        developer.log('❌ 微信SDK未初始化，尝试重新初始化...');
        await _initWeChatSDK();
        if (!_isInitialized.value) {
          ToastUtil.error('微信SDK初始化失败');
          return false;
        }
      }

      // 检查微信是否安装
      if (!_isWeChatInstalled.value) {
        ToastUtil.error('请先安装微信应用');
        return false;
      }

      // 参数验证
      if (title.isEmpty || webUrl.isEmpty) {
        ToastUtil.error('分享标题和链接不能为空');
        return false;
      }

      developer.log('🔗 开始原生分享到微信...');
      developer.log('📝 标题: $title');
      developer.log('📝 描述: $description');
      developer.log('🌐 链接: $webUrl');
      developer.log('🖼️ 缩略图: ${thumbUrl ?? "无"}');
      developer.log('📍 分享场景: ${isTimeline ? "朋友圈" : "好友"}');

      // 调用原生分享方法
      final success = await platform.invokeMethod('shareToWeChat', {
        'title': WeChatConfig.validateTitle(title),
        'description': WeChatConfig.validateDescription(description),
        'webUrl': webUrl,
        'thumbUrl': thumbUrl,
        'isTimeline': isTimeline,
      });

      if (success == true) {
        developer.log('✅ 原生微信分享成功');
        ToastUtil.success('正在跳转到微信...');
        return true;
      } else {
        developer.log('❌ 原生微信分享失败');
        ToastUtil.error('分享失败');
        return false;
      }

    } catch (e) {
      developer.log('💥 原生微信分享异常: $e');
      ToastUtil.error('分享出错: $e');
      return false;
    }
  }

  /// 分享到微信好友
  Future<bool> shareToFriend({
    required String title,
    required String description,
    required String webUrl,
    String? thumbUrl,
  }) async {
    return shareWebPage(
      title: title,
      description: description,
      webUrl: webUrl,
      thumbUrl: thumbUrl,
      isTimeline: false,
    );
  }

  /// 分享到微信朋友圈
  Future<bool> shareToTimeline({
    required String title,
    required String description,
    required String webUrl,
    String? thumbUrl,
  }) async {
    return shareWebPage(
      title: title,
      description: description,
      webUrl: webUrl,
      thumbUrl: thumbUrl,
      isTimeline: true,
    );
  }

  /// 检查微信安装状态并更新
  Future<bool> checkWeChatInstallation() async {
    try {
      final isInstalled = await platform.invokeMethod('isWeChatInstalled');
      _isWeChatInstalled.value = isInstalled ?? false;
      developer.log('🔄 微信安装状态检查: ${_isWeChatInstalled.value}');
      return _isWeChatInstalled.value;
    } catch (e) {
      developer.log('❌ 检查微信安装状态失败: $e');
      return false;
    }
  }

  /// 显示微信分享选择对话框
  /// 
  /// 类似MyApplication2项目的分享对话框
  void showWeChatShareDialog({
    required String title,
    required String description,
    required String webUrl,
    String? thumbUrl,
  }) {
    // 使用独立的分享对话框组件
    WeChatShareDialog.show(
      title: title,
      description: description,
      webUrl: webUrl,
      thumbUrl: thumbUrl,
    );
  }

  /// 获取微信分享URL（通过后端API动态生成）
  /// 🔥 对应MyApplication2项目的实现方式，使用完整的活动和用户信息
  Future<String> generateShareUrl(String activityId, {
    String? activityTitle,
    String? activityDescription,
    List<String>? activityImages,
  }) async {
    try {
      developer.log('🔗 =============== 开始通过API生成分享链接（MyApplication2格式） ===============');
      developer.log('🎯 活动ID: $activityId');
      developer.log('📝 活动标题: ${activityTitle ?? "未提供"}');
      
      // 🔥 获取当前用户信息
      final userService = Get.find<UserService>();
      final currentUser = userService.currentUser;
      
      developer.log('📊 当前用户信息:');
      developer.log('  👤 用户名: ${currentUser?.username ?? "未知"}');
      developer.log('  🚻 性别: ${currentUser?.userGender ?? ""}');
      developer.log('  🏙️ 城市: ${currentUser?.userCity ?? ""}');
      developer.log('  🖼️ 头像: ${currentUser?.userAvatarUrl ?? ""}');
      
      // 🔥 使用ShareApi调用后端获取分享链接（使用MyApplication2的完整参数格式）
      final shareResponse = await ShareApi.createActivityShare(
        activityTitle: activityTitle ?? '精彩活动',
        activityText: activityDescription ?? '我在玩真的发现了一个有趣的活动，快来看看吧！',
        activityImages: activityImages ?? [],
        // 🔥 用户信息（从UserService获取真实用户数据）
        userId: currentUser?.userid.toString() ?? '',
        userNickname: currentUser?.username ?? '玩真的用户',
        userGender: currentUser?.userGender ?? '',
        userCity: currentUser?.userCity ?? '',
        userAvatarUrl: currentUser?.userAvatarUrl ?? '',
      );
      
      if (shareResponse.isSuccess && shareResponse.data?.shareUrl.isNotEmpty == true) {
        final shareUrl = shareResponse.data!.shareUrl;
        developer.log('✅ 通过API成功获取分享链接（MyApplication2格式）: $shareUrl');
        developer.log('🆔 分享ID: ${shareResponse.data!.shareId}');
        return shareUrl;
      } else {
        developer.log('❌ API获取分享链接失败: ${shareResponse.message}');
        developer.log('🔄 降级使用固定格式分享链接');
        // 降级方案：使用固定格式的分享链接
        return WeChatConfig.generateActivityShareUrl(activityId);
      }
    } catch (e) {
      developer.log('💥 API获取分享链接异常: $e');
      developer.log('🔄 降级使用固定格式分享链接');
      // 异常情况：使用固定格式的分享链接作为后备方案
      return WeChatConfig.generateActivityShareUrl(activityId);
    }
  }

  /// 🎨 生成活动分享页面并分享到微信
  /// 
  /// [activity] 活动数据
  /// [shareUrl] 分享链接（可选，如果不提供则自动生成）
  Future<bool> shareActivityWithPage({
    required ActivityModel activity,
    String? shareUrl,
  }) async {
    try {
      developer.log('🎨 开始生成活动分享页面...');
      
      // 生成分享链接（传递完整的活动信息）
      final finalShareUrl = shareUrl ?? await generateShareUrl(
        activity.id,
        activityTitle: activity.title,
        activityDescription: activity.description,
        activityImages: activity.imageUrl.isNotEmpty ? [activity.imageUrl] : [],
      );
      
      // 生成动态分享页面
      final htmlContent = await SharePageGeneratorService.generateActivitySharePage(
        activity: activity,
        shareUrl: finalShareUrl,
      );
      
      // 验证生成的HTML内容
      if (!SharePageGeneratorService.validateHtmlContent(htmlContent)) {
        developer.log('❌ 生成的分享页面内容无效');
        ToastUtil.error('分享页面生成失败');
        return false;
      }
      
      // 保存分享页面到本地文件（用于测试）
      await SharePageGeneratorService.saveSharePageToFile(
        htmlContent: htmlContent,
        activityId: activity.id,
      );
      
      // 生成统计信息
      final stats = SharePageGeneratorService.generateSharePageStats(
        activity: activity,
        shareUrl: finalShareUrl,
      );
      developer.log('📊 分享页面统计: $stats');
      
      // 显示微信分享对话框
      showWeChatShareDialog(
        title: activity.title,
        description: '我在玩真的发现了一个有趣的活动，快来看看吧！',
        webUrl: finalShareUrl,
        thumbUrl: activity.imageUrl.isNotEmpty ? activity.imageUrl : null,
      );
      
      developer.log('✅ 活动分享页面生成完成');
      return true;
      
    } catch (e) {
      developer.log('💥 生成活动分享页面失败: $e');
      ToastUtil.error('分享失败: $e');
      return false;
    }
  }
  
  /// 🔍 预览活动分享页面（开发调试用）
  Future<void> previewActivitySharePage({
    required ActivityModel activity,
    String? shareUrl,
  }) async {
    try {
      final finalShareUrl = shareUrl ?? await generateShareUrl(
        activity.id,
        activityTitle: activity.title,
        activityDescription: activity.description,
        activityImages: activity.imageUrl.isNotEmpty ? [activity.imageUrl] : [],
      );
      
      await SharePageGeneratorService.previewSharePage(
        activity: activity,
        shareUrl: finalShareUrl,
      );
      
      ToastUtil.success('分享页面预览已生成，请查看控制台日志');
    } catch (e) {
      developer.log('💥 预览分享页面失败: $e');
      ToastUtil.error('预览失败: $e');
    }
  }

  /// 重新初始化微信SDK
  Future<bool> reinitialize() async {
    await _initWeChatSDK();
    return _isInitialized.value;
  }
}
